import json
import random

import logging
import uuid
import datetime
import time
import traceback
from flask import jsonify

from dao import redis_connect as rd
from dao.db_connect import db_connect as db

internal_error = 500  # 服务器错误
success = 200  # 请求成功
data_missing = 101  # 数据库内无相关数据
identification_error = 100  # 未识别成功


def getUUID():
    return "".join(str(uuid.uuid4()).split('-')).upper()


class NewsController(object):
    def __init__(self):
        pass

    @classmethod
    def news_list(cls, request):
        """
        新闻列表
        news_type:新闻类型
        title:新闻标题
        id:序列号
        summary:新闻总结
        image_url:图片跳转
        jump_url:跳转链接
        enabled:
        created_at:创建时间
        """
        logging.debug("working on news_list")
        code = success
        msg = "获取新闻列表成功"
        try:
            query_sql = f'select source, title, summary, image_url, jump_url, ' \
                        f'FROM_UNIXTIME(created_at ,"%Y-%m-%d %H:%i:%s") AS create_at from carbon_mini_app.news_list ' \
                        f'limit 10'
            data = db.queryAll(query_sql)
        except Exception as e:
            code = data_missing
            logging.debug(traceback.format_exc())
            msg = "获取新闻列表失败"

        resp = {
            "data": data,
            "msg": msg,
            "code": code,
        }
        return jsonify(resp)

    @classmethod
    def banners(cls, request):
        """
        新闻滑动窗口版
        :return:
        """
        logging.debug("working on banners")
        code = success
        msg = "获取新闻图片成功"
        try:
            query_sql = f'SELECT show_img, jump_url FROM carbon_mini_app.banners LIMIT 3'
            data = db.queryAll(query_sql)
        except Exception as e:
            msg = "获取新闻图片失败"
            code = data_missing
            logging.debug(traceback.format_exc())
        resp = {
            "data": data,
            "msg": msg,
            "code": code,
        }
        return jsonify(resp)
